//@ts-nocheck
import React, { useEffect, useImperativeHandle, useRef, useState } from 'react'
import * as echarts from 'echarts/lib/echarts'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/grid'
import 'echarts/lib/chart/bar'
import selectEmpty from './images/select_empty.png'
import selectFull from './images/select_full.png'
import imageIcon from './images/image_icon.png'
import videoIcon from './images/video_icon.png'

import { Option, ChartsInstance } from './interface'
import './index.less'
let echartsInstance: any = {}
let data: Array<Option> = []

interface IProps {
  chartId?: string
  selectable?: boolean
  onClick?: (options: Array<Option>) => void
  options?: Array<Option>
  width?: number
  chartRef?: React.MutableRefObject<ChartsInstance>
  seriesName?: string
  yUnit?: string
}

const GradualColumn: React.FC<IProps> = ({
  selectable,
  options,
  chartId = '',
  width,
  seriesName = '',
  chartRef,
  onClick,
  yUnit
}) => {
  useEffect(() => {
    echartsInstance[chartId] = echarts.init(document.getElementById(chartId || 'gradual-bar-chart'))
    echartsInstance[chartId].on('click', function () {
      if (selectable) {
        if (params.componentType === 'xAxis' && params.targetType === 'axisLabel') {
          let _clickIndex: number
          data.forEach((item: Option, itemIndex: number) => {
            if (item.choiceContent === params.value) {
              _clickIndex = itemIndex
            }
          })
          if (_clickIndex !== undefined) {
            data[_clickIndex].isSelect = !data[_clickIndex].isSelect
            selectAction()
            setOptions()
          }
        } else if (params.componentType === 'series' && params.componentSubType === 'bar') {
          data[params.dataIndex].isSelect = !data[params.dataIndex].isSelect
          selectAction()
          setOptions()
        }
      } else {
        if (params.componentType === 'xAxis' && params.targetType === 'axisLabel') {
          let _clickIndex: number
          if (params?.event?.target?.parent?.anid) {
            _clickIndex = params?.event?.target?.parent?.anid?.split('_')[1]
          } else {
            data.forEach((item: Option, itemIndex: number) => {
              if (item.choiceContent === params.value) {
                _clickIndex = itemIndex
              }
            })
          }
        }
      }
    })
    setOptions()
  }, [])

  useImperativeHandle(chartRef, () => ({
    getInstance: () => {
      return echartsInstance[chartId]
    }
  }))

  const selectAction = () => {
    onClick?.(
      data.filter((item) => {
        return item.isSelect
      })
    )
  }

  useEffect(() => {
    if (echartsInstance[chartId]) {
      echartsInstance[chartId].resize()
    }
  }, [width])

  useEffect(() => {
    data = options
    if (echartsInstance[chartId]) setOptions()
  }, [options])

  const setOptions = () => {
    let _xAxis = []
    let seriesData = []
    data.forEach((item, itemIndex) => {
      _xAxis.push(item.choiceContent)
      const _barColor = 'rgba(63,96,252, ' + (1 - itemIndex * 0.06) + ')'
      if (item.isSelect) {
        seriesData.push({
          name: item.choiceContent,
          value: item.choiceCount,
          itemStyle: {
            color: _barColor,
            borderWidth: 4,
            borderColor: '#fff',
            shadowColor: 'rgba(0, 10, 59, 0.4)',
            shadowBlur: 10,
            shadowOffsetY: 2
          }
        })
      } else {
        seriesData.push({
          name: item.choiceContent,
          value: item.choiceCount,
          itemStyle: {
            color: _barColor
          }
        })
      }
    })
    echartsInstance[chartId].setOption({
      tooltip: {
        // formatter: yUnit ? `{b}{c}${yUnit}` : `{b}&nbsp;{c}`
      },
      grid: {
        left: '6%',
        top: 10,
        bottom: selectable ? 50 : 30,
        right: '6%'
      },
      xAxis: {
        data: _xAxis,
        axisLabel: {
          show: true,
          interval: 0,
          formatter: (name, dataIndex) => {
            let xName: string = name
            if (options.length > 10 && xName.length > 3) {
              xName = xName.substring(0, 2) + '...'
            } else if (options.length > 0 && xName.length > 8) {
              xName = xName.substring(0, 7) + '...'
            }
            if (!selectable) {
              if (data[dataIndex].type === 1) {
                return `{image|${' '}} {a|${xName}}`
              } else if (data[dataIndex].type === 8) {
                return `{video|${' '}} {a|${xName}}`
              } else {
                return `{a|${xName}}`
              }
            } else {
              if (data[dataIndex].isSelect) {
                return [`{a|${xName}}`, '{c|}'].join('\n')
              } else {
                return [`{a|${xName}}`, '{b|}'].join('\n')
              }
            }
          },
          rich: {
            a: {
              color: '#8B98A9',
              lineHeight: 20,
              fontSize: 10,
              marginBottom: 10,
              padding: [0, 5, 0, 5]
            },
            b: {
              backgroundColor: {
                image: selectEmpty
              },
              width: 16,
              height: 16,
              marginTop: 10
            },
            c: {
              backgroundColor: {
                image: selectFull
              },
              width: 16,
              height: 16,
              marginTop: 10
            },
            image: {
              backgroundColor: {
                image: imageIcon
              },
              width: 16,
              height: 16
            },
            video: {
              backgroundColor: {
                image: videoIcon
              },
              width: 16,
              height: 16
            }
          }
        },
        triggerEvent: true
      },
      yAxis: {
        minInterval: 1,
        axisLabel: {
          formatter: function (value, index) {
            if (yUnit) {
              return `${value} ${yUnit}`
            } else {
              return value
            }
          }
        }
      },
      series: [
        {
          name: seriesName,
          type: 'bar',
          data: [...seriesData],
          itemStyle: {
            borderRadius: [4, 4, 0, 0]
          },
          barMaxWidth: 23
        }
      ]
    })
  }

  return (
    <>
      <div className="gradual-bar-chart" id={chartId || 'gradual-bar-chart'} />
    </>
  )
}
export default (GradualColumn)
